package ltd.trackan.aitextdialogue.model.entity;

import com.alibaba.fastjson2.JSONObject;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.extern.slf4j.Slf4j;
import ltd.trackan.aitextdialogue.model.enumeration.LargeScaleModel;
import ltd.trackan.common.model.entity.RestBean;

import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

/**
 * @author wxa
 */
@Schema(description = "DeepSeek请求实体")
@Slf4j
public class OpenAI {
    @Schema(description = "对话模型")
    private String model = "deepseek-chat";
    
    @Schema(description = "对话记录")
    private final LinkedList<Map<String, Object>> sessionLog = new LinkedList<>();
    
    @Schema(description = "对话是否进行,默认false没有开启对话否则反之")
    private boolean startSession = false;
    
    public OpenAI() {
    }
    
    public String getModel() {
        return model;
    }
    
    public RestBean<String> setModel(String model) {
        if (!LargeScaleModel.isValidModel(model)) {
            return RestBean.failure("模型不正确");
        }
        this.model = model;
        return RestBean.success();
    }
    
    public Queue<Map<String, Object>> getSessionLog() {
        return sessionLog;
    }
    
    // 添加默认系统消息：你是一个乐于助人的助手
    private void initSessionLog() {
        MessageResult system = new MessageResult().role("system").content("You are a helpful assistant, and then you have to answer questions in Chinese in an interesting way");
        if (system.isReady()) {
            sessionLog.offerFirst(JSONObject.parseObject(system.toString()));
        } else {
            log.error("初始化对话历史出现问题");
        }
    }
    
    public RestBean<String> addSessionLog(MessageResult messageResult) {
        if (messageResult == null || !messageResult.isReady()) {
            return RestBean.failure("消息不能为空，或设置错误");
        }
        // 如果是一个新会话初始化
        if (this.sessionLog.isEmpty()) {
            initSessionLog();
        }
        // 如果不是添加assistant助手的内容 并且 上一个会话的历史记录是user用户的内容，则应该是各种原因没有获取助手内容，所以去掉用户的内容
        if (!"assistant".equals(messageResult.getRole()) && "user".equals(String.valueOf(this.sessionLog.getLast().get("role")))) {
            this.sessionLog.pollLast();
        }
        // 转换
        JSONObject jsonObject = JSONObject.parseObject(messageResult.toString());
        this.sessionLog.add(jsonObject);
        // 大于一条初始加15轮对话,就去掉系统和一轮对话，并加上初始对话
        if (sessionLog.size() >= 31) {
            sessionLog.poll();
            sessionLog.poll();
            sessionLog.poll();
            initSessionLog();
        }
        return RestBean.success();
    }
    
    public boolean isStartSession() {
        return startSession;
    }
    
    public void setStartSession(boolean startSession) {
        this.startSession = startSession;
    }
    
    @Override
    public String toString() {
        return String.format(
                "{\"model\":\"%s\",\"sessionLog\":%s,\"startSession\":%s}",
                model,
                sessionLog,
                startSession
        );
    }
    
    @Schema(description = "消息结构")
    public static class MessageResult {
        // 消息角色
        private String role = "user";
        // 消息内容
        private String content;
        
        public boolean isReady() {
            return role != null && content != null;
        }
        
        public String getRole() {
            return role;
        }
        
        public MessageResult role(String role) {
            this.setRole(role);
            return this;
        }
        
        public RestBean<String> setRole(String role) {
            if (role == null || role.isEmpty()) {
                return RestBean.failure("角色不能为空");
            }
            if (!("user".equals(role) || "assistant".equals(role) || "system".equals(role))) {
                return RestBean.failure(role + "角色不正确");
            }
            this.role = role;
            return RestBean.success();
        }
        
        public String getContent() {
            return content;
        }
        
        public MessageResult content(String content) {
            this.setContent(content);
            return this;
        }
        
        public RestBean<String> setContent(String content) {
            if (content == null || content.isEmpty()) {
                return RestBean.failure("内容不能为空");
            }
            if (content.length() > 1000) {
                return RestBean.failure("内容不能超过1000个字符");
            }
            this.content = content;
            return RestBean.success();
        }
        
        @Override
        public String toString() {
            return String.format("{\"role\":\"%s\",\"content\":\"%s\"}", role, content);
        }
    }
}
